#include "thread.h"
#define WHITE_SCREEN 5
#define BLACK_SCREEN 1
//#define SOUND_LIMIT 65
#include <QQueue>

static char getTemp[30]={"lss100.sys.temperature\r"};
static char getCdm2[30]={"lss100.sys.cdm2\r"};
static char getFtl[30]={"lss100.sys.ftl\r"};
static char getCct[30]={"lss100.sys.cct\r"};
static char getSpl[30]={"lss100.sys.spl\r"};
static char getXy[30]={"lss100.sys.xy\r"};
static char getXYZ[30] = {"GETXYZ\r"};
static char getTheaterName[100]={"Lss100.sys.theater_name\r"};
static char getTheaterNo[100] = {"Lss100.sys.theater_number\r"};
static char getIP[32] = {"GetIP\r"};
const static int SOUND_LIMIT = 65;

void static log_print(QString info)
{
    QFile file(QDate::currentDate().toString("yyyy-M-d") + ".log");
    if(!file.open(QIODevice::Append | QIODevice::Text ))
    {
        return;
    }
    QTextStream log_info(&file);

    log_info<<QDateTime::currentDateTime().toString("yyyy-m-d hh:mm:ss")<<"\t"<<info<<"\n";
    file.close();
}

Thread::Thread(QObject *parent) :
    QThread(parent),flag(true), stopped(true)
{
    xyz = {0, 0, 0, 0, 0};
}

void Thread::init()
{
    QString sql = tr("select lc, rc, cc, hb, la, ra from std_test where cinema_hall = '%1' ").arg(device.theaterNo);
    QSqlQueryModel *model = new QSqlQueryModel();
    model->setQuery(sql, db);
    if(model->lastError().isValid())
    {
        emit send_msg(model->lastError().text());
        qDebug()<<sql <<endl;
        exit(0);
    }
    for(int i = 0; i<model->rowCount(); i++)
    {
        std.left_std = model->data(model->index(0, 0)).toDouble();
        std.right_std = model->data(model->index(0, 1)).toDouble();
        std.center_std = model->data(model->index(0, 2)).toDouble();
        std.lfe_std  = model->data(model->index(0, 3)).toDouble();
        std.leftSurround_std = model->data(model->index(0, 4)).toDouble();
        std.rightSurround_std = model->data(model->index(0, 5)).toDouble();
    }

    sql = tr("SELECT"
             " deviation_dcp,"
             " deviation_projector,"
             " deviation_darktime,"
             " deviation_aircondition,"
             " enable_dcp,"
             " enable_projector,"
             " enable_darktime,"
             " enable_aircondition,"
             " theaterNo,"
             " interval_projector,"
             " interval_dcp,"
             " interval_aircondition,"
             " interval_darktime"
             " FROM"
             " autocontrol where theaterNo='%1'").arg(device.theaterNo);
    model->setQuery(sql, db);
    if(model->lastError().isValid())
    {
        emit send_msg(model->lastError().text());
        qDebug()<<sql<<endl;
        exit(0);
    }
    for(int i = 0; i<model->rowCount(); i++)
    {
        auto_parameter.deviation_dcp = model->data(model->index(0, 0)).toDouble();
        auto_parameter.deviation_projector = model->data(model->index(0, 1)).toDouble();
        auto_parameter.deviation_darktime = model->data(model->index(0, 2)).toDouble();
        auto_parameter.deviation_aircondition = model->data(model->index(0, 3)).toDouble();
        auto_parameter.enable_dcp = model->data(model->index(0, 4)).toBool();
        auto_parameter.enable_projector = model->data(model->index(0, 5)).toBool();
        auto_parameter.enable_darktime = model->data(model->index(0, 6)).toBool();
        auto_parameter.enable_aircondition = model->data(model->index(0, 7)).toBool();
        auto_parameter.theaterNo = model->data(model->index(0, 8)).toString();
        auto_parameter.interval_projector = model->data(model->index(0, 9)).toDouble();
        auto_parameter.interval_dcp = model->data(model->index(0, 10)).toDouble();
        auto_parameter.interval_aircondition = model->data(model->index(0, 10)).toDouble();
        auto_parameter.interval_darktime = model->data(model->index(0, 11)).toDouble();

    }


    sql = tr("select ip, port from device where theaterNo= '%1' and type='%2' ").arg(device.theaterNo).arg(tr("数字放映机"));
    model->setQuery(sql, db);
    if(model->lastError().isValid())
    {
        emit send_msg(model->lastError().text());
        qDebug()<<sql<<endl;
        exit(0);
    }
    auto_device_projector.ip = model->data(model->index(0, 0)).toString();
    auto_device_projector.port = model->data(model->index(0, 1)).toInt();

    sql = tr("select ip, port,  width, height from device where theaterNo='%1' and type='%2'").arg(device.theaterNo).arg("音频处理器");
    model->setQuery(sql, db);
    if(model->lastError().isValid())
    {
        emit send_msg(model->lastError().text());
        qDebug()<<sql<<endl;
        exit(0);
    }

    auto_device_dcp.ip = model->data(model->index(0, 0)).toString();
    auto_device_dcp.port = model->data(model->index(0, 1)).toInt();
    auto_device_dcp.screen_width = model->data(model->index(0, 2)).toDouble();
    auto_device_dcp.screen_height = model->data(model->index(0, 3)).toDouble();


    delete model;
    model = NULL;

}

void Thread::setTestModel(int testModel)
{
    switch(testModel)
    {
    case WANDA_MODEL:
        test_model = WANDA_MODEL;
        break;
    case LEONIS_MODEL:
        test_model = LEONIS_MODEL;
        break;
    case SERVER_MODEL:
        test_model = SERVER_MODEL;
        break;
    }
}

void Thread::run()
{
    while(flag)
    {
        QTime currTime = QTime::currentTime();
        while((currTime >= device.stime && currTime <= device.etime) )
        {
            if(!connect(socket))break;
            switch(test_model)
            {
            case WANDA_MODEL:
            {
                if(!CheckWanda())
                {
                    continue;
                }
                if(!stopped)
                    TestWanda();
            } break;
            case LEONIS_MODEL:
            {
                if(!CheckWanda())
                {
                    continue;
                }
                if(!stopped)
                    test();
            }break;
            case SERVER_MODEL:
            {
                if(!CheckServer())
                {
                    continue;
                }
                if(!stopped)
                    TestServer();
            }
            }
            if(!flag)break;
        }
    }
    if(socket.isOpen())socket.close();
    emit send_msg("线程停止");
}

bool Thread::CheckServer()
{
    return true;
}

void Thread::TestServer()
{
    try
    {
        sleep(3);
        stime = QDateTime::currentDateTime();
        qDebug()<<"start test white light:"<<endl;
        emit log_info(device.theaterNo + ", start test white light:");
        white_ftl = read_one(getFtl, socket).toDouble() + device.fix_ftl;

        //00:02--00:07
        sleep(SLEEP_TIME);
        qDebug()<<"start test red XY:"<<endl;
        emit log_info(device.theaterNo + ", start test red XY:");
        red_ftl = read_one(getFtl, socket).toDouble();
        read_xy(getXy, rx, ry, socket);

        //00:07-00:12
        sleep(SLEEP_TIME);
        qDebug()<<"start test green light:"<<endl;
        emit log_info(device.theaterNo + ", start test green light:");
        green_ftl = read_one(getFtl, socket).toDouble();
        read_xy(getXy, gx, gy, socket);

        sleep(SLEEP_TIME);
        qDebug()<<"start blue ftl:"<<endl;
        emit log_info(device.theaterNo + ", start blue ftl:");
        blue_ftl = read_one(getFtl, socket).toDouble();
        read_xy(getXy, bluex, bluey, socket);
        //00:17--00:22
        sleep(SLEEP_TIME);
        qDebug()<<"start test left sound:"<<endl;
        emit log_info(device.theaterNo + ", start test left sound:");
        l_spl = read_one(getSpl, socket).toDouble() + device.fix_lc;
        splValue.leftSpl = l_spl;
        //00:22--00:27
        sleep(SLEEP_TIME);
        qDebug()<<"start test right sound:"<<endl;
        emit log_info(device.theaterNo + ", start test right sound:");
        r_spl = read_one(getSpl, socket).toDouble() + device.fix_rc;
        splValue.rightSpl = r_spl;
        //00:27--00:32
        sleep(SLEEP_TIME);
        qDebug()<<"start test center sound:"<<endl;
        emit log_info(device.theaterNo + ", start test center sound:");
        c_spl = read_one(getSpl, socket).toDouble() + device.fix_cc;
        splValue.centerSpl = c_spl;
        //00:32--00:37
        sleep(SLEEP_TIME);
        qDebug()<<"start test heavy  sound:"<<endl;
        emit log_info(device.theaterNo + ", start test heavy  sound:");
        lfe_spl = read_one(getSpl, socket).toDouble() + device.fix_hb;
        splValue.lfeSpl = lfe_spl;
        //00:37--00:42
        sleep(SLEEP_TIME);
        qDebug()<<"start test left  around:"<<endl;
        emit log_info(device.theaterNo + ", start test left  around::");
        ls_spl = read_one(getSpl, socket).toDouble() + device.fix_la;
        splValue.leftSurroundSpl = ls_spl;
        //00:42--00:47
        sleep(SLEEP_TIME);
        qDebug()<<"start test right around:"<<endl;
        emit log_info(device.theaterNo + ", start test right around:");

        rs_spl = read_one(getSpl, socket).toDouble() + device.fix_ra;
        splValue.rightSurroundSpl = rs_spl;
        //00:47--00:52
        sleep(SLEEP_TIME);
        qDebug()<<"start test ll  sound:"<<endl;
        emit log_info(device.theaterNo + ", start test ll  sound:");
        ll_spl = read_one(getSpl, socket).toDouble() + 0;

        //00:52--00:57
        sleep(SLEEP_TIME);
        qDebug()<<"start test rl  sound:"<<endl;
        emit log_info(device.theaterNo + ", start test rl  sound:");
        rl_spl = read_one(getSpl, socket).toDouble() + 0;

        //00:52--00:54
        sleep(SLEEP_TIME);
        qDebug()<<"start test temp  sound:"<<endl;
        emit log_info(device.theaterNo + ", start test temp  sound:");
        read_xy(getTemp, temper_c, temper_f, socket);
        w_cct = read_one(getCct, socket).toDouble();

        cinema_name = read_data(getTheaterName, socket);
        cinema_hall = read_data(getTheaterNo, socket);
        dev_ip = read_data(getIP, socket);

        etime = QDateTime::currentDateTime();
        qDebug()<<"insert db."<<endl;
        mutex.lock();
        insert();
        dolaser();
        mutex.unlock();
        emit send_progress_value(1);
        sleep(SLEEP_TIME);
    }
    catch (QString e)
    {
        printf("%s\n", e.toStdString().c_str());
    }
    qDebug()<<device.ip<<endl;
}

void Thread::Stop(volatile bool flag)
{
    this->flag = !flag; // 设置线程停止标志
    this->stopped = flag;
}

void Thread::setDB(QSqlDatabase db)
{
    this->db = db;
}

void Thread::setDevice(Device dev)
{
    this->device = dev;
}

void Thread::setFix()
{
    this->white_ftl = white_ftl + device.fix_ftl;
    this->l_spl = l_spl + device.fix_lc;
    this->r_spl = r_spl + device.fix_rc;
    this->c_spl = c_spl + device.fix_cc;
    this->lfe_spl = lfe_spl + device.fix_hb;
    this->ll_spl = ll_spl + device.fix_la;
    this->rl_spl = rl_spl + device.fix_ra;
}

void Thread::insert()
{
    QString sql = QString(QObject::tr("insert into tb_dev_test_results("
                                      "cinema_name, cinema_hall, dev_ip,"
                                      "lc, rc, cc, hb, la, ra, cct, "
                                      "wx, wy, rx, ry, gx, gy, bluex, bluey,"
                                      "white_ftl, red_ftl, green_ftl, blue_ftl,"
                                      "temper_c, temper_f, stime, etime, left_after, right_after"
                                      ")values("
                                      "'%1', '%2', '%3',"
                                      "'%4', '%5', '%6', '%7', '%8', '%9', '%10', "
                                      "'%11', '%12', '%13', '%14', '%15', '%16', '%17', '%18',"
                                      "'%19', '%20', '%21', '%22',"
                                      "'%23', '%24', '%25', '%26', "
                                      "'%27', '%28' "
                                      ");"
                                      ).arg(cinema_name).arg( cinema_hall).arg( dev_ip)
                          .arg(l_spl).arg(r_spl).arg(c_spl).arg(lfe_spl).arg(ll_spl).arg(rl_spl).arg(w_cct)
                          .arg(wx).arg(wy).arg(rx).arg(ry).arg(gx).arg(gy).arg(bluex).arg(bluey)
                          .arg(white_ftl).arg(red_ftl).arg(green_ftl).arg(blue_ftl)
                          .arg(temper_c).arg(temper_f).arg(stime.toString("yyyy-MM-dd hh:mm:ss")).arg(etime.toString("yyyy-MM-dd hh:mm:ss"))
                          .arg(0.0).arg(0.0)
                          );

    cout<<sql.toStdString()<<endl;
    proc_sql(sql);
}

QString Thread::read_data(char *s, QTcpSocket &socket)
{
    char buf[50];
    socket.write(s, strlen(s));
    if(!socket.waitForBytesWritten())
        throw socket.errorString();
    memset(buf, 0, 50);
    if (!socket.waitForReadyRead())
        throw socket.errorString();
    socket.read(buf, 50);
    return QString::fromLocal8Bit(buf);
}

QString Thread::read_one(char *s, QTcpSocket &socket)
{
    char buf[50];
    socket.write(s, strlen(s));
    if(!socket.waitForBytesWritten(-1))
        throw socket.errorString();
    memset(buf, 0, 50);
    if (!socket.waitForReadyRead(-1))
        throw socket.errorString();
    socket.read(buf, 50);
//    qDebug()<<"I have receive: "<<buf<<endl;
    log_print("I have receive:" + QString::fromLocal8Bit(buf));
    QString tt = auto_device_dcp.ip;
    tt += " I have receive: ";
    tt += QString::fromLocal8Bit(buf);
    emit log_info(tt);
    //emit log_info(auto_device_dcp.ip + "I have receive: " + QString::fromLocal8Bit(buf));
    QString t = QString::fromLocal8Bit(buf);
    return t.split("\t").at(0);
}

bool Thread::read_xy(char *s, float &x, float &y, QTcpSocket &socket)
{
    QString result = read_data(s, socket);
    QStringList slist = result.split("\t");
    if (slist.size()>= 2)
    {
        x = slist[0].toFloat();
        y = slist[1].toFloat();
        return true;
    }
    return false;
}

bool Thread::connect(QTcpSocket &socket)
{
    socket.connectToHost(device.ip, device.port);
    if (!socket.waitForConnected(3000)) {
        emit send_msg(tr("连接ip为%1设备出错, 请检查设备或网络环境！").arg(device.ip));
        return false;
    }
    return true;
}

void Thread::sleep(long sec)
{
#ifdef WIN32
    Sleep(sec*1000);
#else
    QThread::sleep(sec);
#endif
}

/****************************************************************************
 *
 * 万达模式的测试入口检测
 *
 *
 * return
 *****************************************************************************/
bool Thread::CheckWanda()
{
    double ftl = 0.0;
    int count_white = 0;
    int count_black = 0;
    int cnt = 0;

    QQueue<float> queue;
    QQueue<int> q1, q2, q3, q4;
    int oneflag = 0;
    while(!stopped)
    {
        ftl = read_one(getFtl, socket).toDouble();
        msleep(10);
        white_ftl = ftl;
        switch(oneflag)
        {
        case 0:
            if(q1.size()>50)
                q1.dequeue();
            if(ftl > 1)
                q1.enqueue(1);
            else if(ftl < 0.4 && q1.size() > 8)
            {
                q2.clear();
                q2.enqueue(0);
                oneflag = 1;
            }
            else {
                q1.clear();
            }
            break;
        case 1:
            if(q2.size()>50)
                q2.dequeue();
            if(ftl < 0.4)
                q2.enqueue(0);
            else if(ftl > 1 && q2.size() > 12)
            {
                q3.clear();
                q3.enqueue(1);
                oneflag = 2;
            }
            else {
                q1.clear();
                oneflag = 0;
            }
            break;
        case 2:
            if(q3.size()>50)
                q3.dequeue();
            if(ftl > 1)
                q3.enqueue(1);
            else if(ftl < 0.4 && q3.size() > 8)
            {
                q4.clear();
                q4.enqueue(0);
                oneflag = 3;
            }
            else
            {
                q1.clear();
                oneflag = 0;
            }
            break;
        case 3:
            if(q4.size()>50)
                q4.dequeue();
            if(ftl < 0.4)
            {
                q4.enqueue(0);
                if(q1.size() > 8 && q2.size() > 12 && q3.size() > 8 && q4.size() > 12)
                {
                    return true;
                }
            }
            else if(ftl > 1 && q4.size() > 12 && q4.size() < 50)
            {
                if(q1.size() > 8 && q2.size() > 12 && q3.size() > 8 && q4.size() > 12)
                {
                    return true;
                }
            }
            else
            {
                q1.clear();
                oneflag = 0;
            }
            break;
        }

        QTime currTime = QTime::currentTime();
        if((currTime < device.stime && currTime > device.etime))
            return false;
    }
    return false;

}



/****************************************************************************
 *
 *  万达模式测试流程
 * param
 * param
 * param
 * return
 *****************************************************************************/
void Thread::TestWanda()
{
#if 1
    try
    {
        emit log_info("<p><h1><font color=red >start test</font></h1></p>");
        stime = QDateTime::currentDateTime();
        qDebug()<<"start test white light:"<<endl;
        //        emit log_info(device.theaterNo + ", start test white light:");
        //        white_ftl = read_one(getFtl, socket).toDouble() + device.fix_ftl;
        //        sleep(SLEEP_TIME);

        qDebug()<<"start test right sound:"<<endl;
        emit log_info(device.theaterNo + ", start test right sound:");
        r_spl = read_one(getSpl, socket).toDouble() + device.fix_rc;
        splValue.rightSpl = r_spl;
        sleep(SLEEP_TIME);
        qDebug()<<"start test center sound:"<<endl;
        emit log_info(device.theaterNo + ", start test center sound:");
        c_spl = read_one(getSpl, socket).toDouble() + device.fix_cc;
        splValue.centerSpl = c_spl;

        sleep(SLEEP_TIME);
        qDebug()<<"start test left sound:"<<endl;
        emit log_info(device.theaterNo + ", start test left sound:");
        l_spl = read_one(getSpl, socket).toDouble() + device.fix_lc;
        splValue.leftSpl = l_spl;

        sleep(SLEEP_TIME);
        qDebug()<<"start test heavy  sound:"<<endl;
        emit log_info(device.theaterNo + ", start test heavy  sound:");
        lfe_spl = read_one(getSpl, socket).toDouble() + device.fix_hb;
        splValue.lfeSpl = lfe_spl;

        sleep(SLEEP_TIME);
        qDebug()<<"start test right around:"<<endl;
        emit log_info(device.theaterNo + ", start test right around:");

        sleep(SLEEP_TIME);
        qDebug()<<"start test left  around:"<<endl;
        emit log_info(device.theaterNo + ", start test left  around::");
        ls_spl = read_one(getSpl, socket).toDouble() + device.fix_la;
        splValue.leftSurroundSpl = ls_spl;

        rs_spl = read_one(getSpl, socket).toDouble() + device.fix_ra;
        splValue.rightSurroundSpl = rs_spl;

        sleep(SLEEP_TIME);
        qDebug()<<"start test ll  sound:"<<endl;
        emit log_info(device.theaterNo + ", start test ll  sound:");
        ll_spl = read_one(getSpl, socket).toDouble() + 0;

        sleep(SLEEP_TIME);
        qDebug()<<"start test rl  sound:"<<endl;
        emit log_info(device.theaterNo + ", start test rl  sound:");
        rl_spl = read_one(getSpl, socket).toDouble() + 0;

        cinema_name = read_data(getTheaterName, socket);
        cinema_hall = read_data(getTheaterNo, socket);
        dev_ip = read_data(getIP, socket);

        etime = QDateTime::currentDateTime();
        qDebug()<<"insert db."<<endl;
        mutex.lock();
        insert();
        dolaser();
        mutex.unlock();
        emit send_progress_value(1);
        sleep(SLEEP_TIME);
    }
    catch (QString e)
    {
        printf("%s\n", e.toStdString().c_str());
    }
    qDebug()<<device.ip<<endl;
#endif
}

/****************************************************************************
 *
 * LEONIS 模式的测试入口检测
 * param
 * param
 * param
 * return
 *****************************************************************************/
bool Thread::checkStart()
{
    while(1)
    {
        if ((read_one(getSpl, socket).toDouble() +
             device.fix_lc) > SOUND_LIMIT)
            break;
        sleep(1);
    }
    bool prev_flag = (read_one(getFtl, socket).toDouble()+ device.fix_ftl) > WHITE_SCREEN?true:false;
    int count = 0;
    while(1)
    {
        bool cur_flag = (read_one(getFtl, socket).toDouble()+device.fix_ftl) > WHITE_SCREEN?true:false;
        if (prev_flag != cur_flag && (read_one(getSpl, socket).toDouble()+device.fix_lc) > SOUND_LIMIT)
        {
            prev_flag = cur_flag;
            count++;
        }
    }
    if(count > 3)
        return true;
    else
        return false;

}

/****************************************************************************
 *
 * LEONIS 模式的測試流程
 * param
 * param
 * param
 * return
 *****************************************************************************/
void Thread::test()
{
    try
    {
        //00:00--00:05
        sleep(9);
        stime = QDateTime::currentDateTime();
        qDebug()<<"start test white light:"<<endl;
        emit log_info(device.theaterNo + ", start test white light:");
        white_ftl = read_one(getFtl, socket).toDouble() + device.fix_ftl;

        sleep(SLEEP_TIME);
        qDebug()<<"start test red XY:"<<endl;
        emit log_info(device.theaterNo + ", start test red XY:");
        red_ftl = read_one(getFtl, socket).toDouble();
        read_xy(getXy, rx, ry, socket);

        //00:07-00:12
        sleep(SLEEP_TIME);
        qDebug()<<"start test green light:"<<endl;
        emit log_info(device.theaterNo + ", start test green light:");
        green_ftl = read_one(getFtl, socket).toDouble();
        read_xy(getXy, gx, gy, socket);

        sleep(SLEEP_TIME);
        qDebug()<<"start blue ftl:"<<endl;
        emit log_info(device.theaterNo + ", start blue ftl:");
        blue_ftl = read_one(getFtl, socket).toDouble();
        read_xy(getXy, bluex, bluey, socket);
        //00:17--00:22
        sleep(SLEEP_TIME);
        qDebug()<<"start test left sound:"<<endl;
        emit log_info(device.theaterNo + ", start test left sound:");
        l_spl = read_one(getSpl, socket).toDouble() + device.fix_lc;
        splValue.leftSpl = l_spl;
        //00:22--00:27
        sleep(SLEEP_TIME);
        qDebug()<<"start test right sound:"<<endl;
        emit log_info(device.theaterNo + ", start test right sound:");
        r_spl = read_one(getSpl, socket).toDouble() + device.fix_rc;
        splValue.rightSpl = r_spl;
        //00:27--00:32
        sleep(SLEEP_TIME);
        qDebug()<<"start test center sound:"<<endl;
        emit log_info(device.theaterNo + ", start test center sound:");
        c_spl = read_one(getSpl, socket).toDouble() + device.fix_cc;
        splValue.centerSpl = c_spl;
        //00:32--00:37
        sleep(SLEEP_TIME);
        qDebug()<<"start test heavy  sound:"<<endl;
        emit log_info(device.theaterNo + ", start test heavy  sound:");
        lfe_spl = read_one(getSpl, socket).toDouble() + device.fix_hb;
        splValue.lfeSpl = lfe_spl;
        //00:37--00:42
        sleep(SLEEP_TIME);
        qDebug()<<"start test left  around:"<<endl;
        emit log_info(device.theaterNo + ", start test left  around::");
        ls_spl = read_one(getSpl, socket).toDouble() + device.fix_la;
        splValue.leftSurroundSpl = ls_spl;
        //00:42--00:47
        sleep(SLEEP_TIME);
        qDebug()<<"start test right around:"<<endl;
        emit log_info(device.theaterNo + ", start test right around:");

        rs_spl = read_one(getSpl, socket).toDouble() + device.fix_ra;
        splValue.rightSurroundSpl = rs_spl;
        //00:47--00:52
        sleep(SLEEP_TIME);
        qDebug()<<"start test ll  sound:"<<endl;
        emit log_info(device.theaterNo + ", start test ll  sound:");
        ll_spl = read_one(getSpl, socket).toDouble() + 0;

        //00:52--00:57
        sleep(SLEEP_TIME);
        qDebug()<<"start test rl  sound:"<<endl;
        emit log_info(device.theaterNo + ", start test rl  sound:");
        rl_spl = read_one(getSpl, socket).toDouble() + 0;

        //00:52--00:54
        sleep(SLEEP_TIME);
        qDebug()<<"start test temp  sound:"<<endl;
        emit log_info(device.theaterNo + ", start test temp  sound:");
        read_xy(getTemp, temper_c, temper_f, socket);
        w_cct = read_one(getCct, socket).toDouble();

        cinema_name = read_data(getTheaterName, socket);
        cinema_hall = read_data(getTheaterNo, socket);
        dev_ip = read_data(getIP, socket);

        etime = QDateTime::currentDateTime();
        qDebug()<<"insert db."<<endl;
        mutex.lock();
        insert();
        dolaser();
        mutex.unlock();
        emit send_progress_value(1);
        sleep(SLEEP_TIME);
    }
    catch (QString e)
    {
        printf("%s\n", e.toStdString().c_str());
    }
    qDebug()<<device.ip<<endl;
}

void Thread::recv_msg(const QString msg)
{
    if(!flag)return;
    response = msg;
    qDebug()<<response;
    QString pattern = "top.ctrlframe.statusF.document.stat.textfield.value='";
    QRegExp regExp(pattern);
    if(response.contains(regExp))
    {
        int position = response.indexOf(pattern)+pattern.length();
        int len = 3;
        using_time = response.mid(position, len).toDouble();
        qDebug()<<using_time<<endl;
    }

    pattern = "top.ctrlframe.statusF.document.stat.textfield2.value='";
    regExp.setPattern(pattern);
    if(response.contains(regExp))
    {
        int position = response.indexOf(pattern)+pattern.length();
        int len = 2;
        power = response.mid(position, len).toDouble();
        qDebug()<<power<<endl;
    }


    pattern = "mfr.SetLampAdj(";
    regExp.setPattern(pattern);
    QString current_s;
    if(response.contains(pattern))
    {
        int position = response.indexOf(pattern) + pattern.length();
        int len = 3;
        current = response.mid(position, len).toDouble()/10.0;
        qDebug()<<current<<endl;
        //        current_s.insert(2, '.');
    }

    pattern = "mfr.SetLampText(3, \"";
    if(response.contains(pattern))
    {
        int position = response.indexOf(pattern) + pattern.length();
        int len = 4;
        power_w = response.mid(position, len).toDouble();
        qDebug()<<power_w<<endl;
    }

    QTime t;
    t= QTime::currentTime();
    qsrand(t.msec()+t.second()*1000);
    int n = qrand();

    dcp_gain = n;
    char cmd[255] = {};
    sprintf(cmd, "insert into tb_analysis(current, power, power_w, dcp_gain, using_time, theaterNo, datetime)"
            "values('%.4f', '%.4f', '%.4f', '%.4f', '%.4f', '%s', '%s');",
            current, power, power_w, dcp_gain,
            using_time, device.theaterNo.toLocal8Bit().data(),
            QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss").toLocal8Bit().data());
    QString sql = QString::fromLocal8Bit(cmd);
    qDebug()<<sql<<endl;

    QSqlQueryModel *model = new QSqlQueryModel();
    model->setQuery(sql, db);
    if(model->lastError().isValid())
    {
        emit send_msg(model->lastError().text());
        qDebug()<<model->lastError().text()<<endl;
        emit send_msg(sql);
    }
    delete model;
    model = NULL;
}

void Thread::analysis()
{
    getProjector();
    double L ;
    double Lumen;
    double Pg;
    double Area;
    double height;
    double width;


    QSqlQueryModel *model = new QSqlQueryModel();

    QString sql = tr("select white_ftl from tb_dev_test_results where cinema_hall = '%1' order by id desc limit 1").arg(device.theaterNo);
    model->setQuery(sql, db);
    if(model->lastError().isValid())
    {
        emit send_msg(model->lastError().text());
        qDebug()<<sql<<endl;
        emit send_msg(sql);
        exit(0);
        flag = false;
    }
    Lumen = model->data(model->index(0, 0)).toDouble();

    sql = tr("select width, height, gain from device where theaterNo = '%1' and type='%2' ").arg(device.theaterNo).arg(tr("银幕"));
    model->setQuery(sql, db);
    if(model->lastError().isValid())
    {
        emit send_msg(model->lastError().text());
        qDebug()<<sql<<endl;
        emit send_msg(sql);
        exit(0);
        flag = false;
    }

    width = model->data(model->index(0, 0)).toDouble();
    height = model->data(model->index(0, 1)).toDouble();
    Pg = model->data(model->index(0, 2)).toDouble();

    Area = width*height;
    L = (Pg*Lumen)/(Area*PI);

    qDebug()<<"L="<<L<<endl;

    sql = tr("select current, power, power_w, dcp_gain, using_time from tb_analysis where theaterNo = '%1' order by id desc limit 1 ")
            .arg(device.theaterNo);
    model->setQuery(sql, db);
    if(model->lastError().isValid())
    {
        emit send_msg(model->lastError().text());
        qDebug()<<sql<<endl;
        emit send_msg(sql);
        exit(0);
        flag = false;
    }

    double power_w_temp = model->data(model->index(0, 2)).toDouble();
    double using_time_temp = model->data(model->index(0, 4)).toDouble();

    QString currDateTime = QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss");
    sql = tr("insert into analysis_light_sys(power, bright, bright_std, using_time, theaterNo, datetime)"
             " values (%1, %2, %3, '%4', '%5', '%6');")
            .arg(power_w_temp).arg(Lumen).arg(L).arg(using_time_temp).arg(device.theaterNo).arg(currDateTime);
    model->setQuery(sql, db);
    if(model->lastError().isValid())
    {
        emit send_msg(model->lastError().text());
        emit send_msg(sql);
        qDebug()<<model->lastError().text()<<endl;
        qDebug()<<sql<<endl;
        emit send_msg(sql);
        exit(0);
    }

    qDebug()<<"分析"<<endl;
    sql = tr("INSERT INTO analysis_sound_sys ("
             " analysis_sound_sys.leftSpl,"
             " analysis_sound_sys.rightSpl,"
             " analysis_sound_sys.centerSpl,"
             " analysis_sound_sys.lfeSpl,"
             " analysis_sound_sys.leftSurroundSpl,"
             " analysis_sound_sys.rightSurroundSpl,"
             " analysis_sound_sys.left_std,"
             " analysis_sound_sys.right_std,"
             " analysis_sound_sys.center_std,"
             " analysis_sound_sys.lfe_std,"
             " analysis_sound_sys.leftSurround_std,"
             " analysis_sound_sys.rightSurround_std,"
             " analysis_sound_sys.theaterNo,"
             " analysis_sound_sys.datetime "
             ") values("
             " %1, %2, %3, %4, %5, %6,"
             " %7, %8, %9, %10, %11, %12, '%13', '%14');"
             ).arg(splValue.leftSpl)
            .arg(splValue.rightSpl)
            .arg(splValue.centerSpl)
            .arg(splValue.lfeSpl)
            .arg(splValue.leftSurroundSpl)
            .arg(splValue.rightSurroundSpl)
            .arg(std.left_std)
            .arg(std.right_std)
            .arg(std.center_std)
            .arg(std.lfe_std)
            .arg(std.leftSurround_std)
            .arg(std.rightSurround_std)
            .arg(device.theaterNo)
            .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    model->setQuery(sql, db);
    if(model->lastError().isValid())
    {
        qDebug()<<sql <<endl;
        qDebug()<<model->lastError().text()<<endl;
        emit send_msg(sql);
        exit(0);
    }
}


void Thread::automaticalTuning()
{
    qDebug()<<"自动调校"<<endl;
    //dcp
    //projector
    double current = getProjector();
    if(l_spl > 85.0)
    {
        double v = dcp_gain + dcp_gain*auto_parameter.deviation_dcp;
        if(v <4 && v > 9)
            setDcpGain(v);
    }

    if(l_spl < 85.0)
    {
        double v = dcp_gain = dcp_gain*auto_parameter.deviation_dcp;
        if(v>4&&v<9)
            setDcpGain(v);
    }

    if(white_ftl < 14.0 )
    {
        double v = current + current*auto_parameter.deviation_projector;
        if(v > 77.0 && v<108.0)
            setLampCurrent(v);
    }

    if(white_ftl > 14.0 )
    {
        double v = current - current*auto_parameter.deviation_projector;
        if(v > 77.0 && v<108.0)
            setLampCurrent(v);
    }
    //darktime
    //air-condition
}

double Thread::getDcpGain()
{
    //连接主机
    //获取增益
    //返回结果
}

void Thread::setDcpGain(double v)
{

}

void Thread::setLampCurrent(double v)
{
    QString url = tr("http://%1/cgi-bin/lampadjEng.cgi?v=%2%000000").arg(auto_device_projector.ip).arg(v);
    http.setReq(url);

}

double Thread::getProjector()
{
    initDeviceHost();
    //发送http请求
    QObject::connect(&http, SIGNAL(send_msg(const QString )), this, SLOT(recv_msg(const QString) ));
    QString url = tr("http://%1/cgi-bin/statusEng.cgi?D=%02%99%191923").arg(projectorIP);
    http.setReq(url);
    http.start();

    //取得响应报文
    //查找电流数据
    //转换成double
    //返回结果
}

void Thread::initDeviceHost()
{

    QSqlQueryModel *model = new QSqlQueryModel();
#if 0
    QString sql = tr("select device.ip, device.port from device where theaterNo = '%1' and type = '%2'").arg(device.theaterNo).arg(tr("音频处理器"));
    model->setQuery(sql, db);
    if(model->lastError().isValid())
    {
        emit send_msg(model->lastError().text());
        qDebug()<<model->lastError().text()<<endl;
        emit send_msg(sql);
        exit(0);
    }

    QString ip = model->data(model->index(0, 0)).toString();
    int port = model->data(model->index(0, 1)).toInt();
    DeviceHost dh = {ip, port, tr("音频处理器")};
    device_host_list.clear();
    device_host_list.push_back(dh);
#endif

    QString sql = tr("select ip, port from device where theaterNo = '%1' and type = '%2'").arg(device.theaterNo).arg(tr("数字放映机"));
    model->setQuery(sql, db);
    if(model->lastError().isValid())
    {
        emit send_msg(model->lastError().text());
        qDebug()<<model->lastError().text()<<endl;
        emit send_msg(sql);
    }
    QString ip = model->data(model->index(0, 0)).toString();
    int  port = model->data(model->index(0, 1)).toInt();
    DeviceHost dh = {ip, port, tr("数字放映机") };
    device_host_list.push_back(dh);
    projectorIP = ip;





}

void Thread::read_XYZ(char *s, QTcpSocket &socket)
{
    QString result = read_data(s, socket);
    QStringList slist = result.split(" ");
    if (slist.size()>= 3)
    {
        double X = slist[0].toFloat();
        double Y = slist[1].toFloat();
        double Z = slist[2].toFloat();
        xyz.X = X;
        xyz.Y = Y;
        xyz.Z = Z;
        if(X == 0.0)
            xyz.x = 0.0;
        if(Y == 0.0)
            xyz.y = 0.0;
        if(X != 0.0 && Y!= 0.0)
        {
            xyz.x = xyz.X/(xyz.X + xyz.Y + xyz.Z);
            xyz.y = xyz.Y/(xyz.X + xyz.Y + xyz.Z);
        }
    }
}

void Thread::dolaser()
{

    read_XYZ(getXYZ, socket);
    laser.rx1 = xyz.x;
    laser.ry1 = xyz.y;
    laser.URX1 = xyz.X;
    laser.URY1 = xyz.Y;
    laser.URZ1 = xyz.Z;
    sleep(SLEEP_TIME);
    read_XYZ(getXYZ, socket);
    laser.gx1 = xyz.x;
    laser.gy1 = xyz.y;
    laser.UgX1 = xyz.X;
    laser.UgY1 = xyz.Y;
    laser.UgZ1 = xyz.Z;
    sleep(SLEEP_TIME);
    read_XYZ(getXYZ, socket);
    laser.bx1 = xyz.x;
    laser.by1 = xyz.y;
    laser.UbX1 = xyz.X;
    laser.UbY1 = xyz.Y;
    laser.UbZ1 = xyz.Z;
    sleep(SLEEP_TIME);
    read_XYZ(getXYZ, socket);
    laser.rx2 = xyz.x;
    laser.ry2 = xyz.y;
    laser.URX2 = xyz.X;
    laser.URY2 = xyz.Y;
    laser.URZ2 = xyz.Z;
    sleep(SLEEP_TIME);
    read_XYZ(getXYZ, socket);
    laser.gx2 = xyz.x;
    laser.gy2 = xyz.y;
    laser.UgX2 = xyz.X;
    laser.UgY2 = xyz.Y;
    laser.UgZ2 = xyz.Z;
    sleep(SLEEP_TIME);
    read_XYZ(getXYZ, socket);
    laser.bx2 = xyz.x;
    laser.by2 = xyz.y;
    laser.UbX2 = xyz.X;
    laser.UbY2 = xyz.Y;
    laser.UbZ2 = xyz.Z;
    laser.theaterNo = device.theaterNo;

    QString sql = tr("insert into tb_laser("
                     "rx1, ry1, URX1, URY1, URZ1, "
                     "gx1, gy1, UgX1, UgY1, UgZ1, "
                     "bx1, by1, UbX1, UbY1, UbZ1, "
                     "rx2, ry2, URX2, URY2, URZ2, "
                     "gx2, gy2, UgX2, UgY2, UgZ2, "
                     "bx2, by2, UbX2, UbY2, UbZ2, theaterNo ) values("
                     "%1, %2, %3, %4, %5, "
                     "%6, %7, %8, %9, %10, "
                     "%11, %12, %13, %14, %15,"
                     "%16, %17, %18, %19, %20, "
                     "%21, %22, %23, %24, %25, "
                     "%26, %27, %28, %29, %30, '%31'"
                     ");"
                     )
            .arg(laser.rx1).arg(laser.ry1).arg(laser.URX1).arg(laser.URY1).arg(laser.URZ1)
            .arg(laser.gx1).arg(laser.gy1).arg(laser.UgX1).arg(laser.UgY1).arg(laser.UgZ1)
            .arg(laser.bx1).arg(laser.by1).arg(laser.UbX1).arg(laser.UbY1).arg(laser.UbZ1)
            .arg(laser.rx2).arg(laser.ry2).arg(laser.URX2).arg(laser.URY2).arg(laser.URZ2)
            .arg(laser.gx2).arg(laser.gy2).arg(laser.UgX2).arg(laser.UgY2).arg(laser.UgZ2)
            .arg(laser.bx2).arg(laser.by2).arg(laser.UbX2).arg(laser.UbY2).arg(laser.UbZ2)
            .arg(laser.theaterNo);

    QString sql2 = tr("delete from tb_laser where theaterNo = '%1'").arg(device.theaterNo);
    emit proc_sql(sql2);
    emit proc_sql(sql);


}

void Thread::setAutoDev()
{

}

